package com.fsy.its.netty.dtu.decoder;

import com.fsy.its.entity.Dtu;
import com.fsy.its.netty.config.DtuDecoder;
import com.fsy.its.netty.dtu.DtuIdDecoder;
import com.fsy.its.netty.dtu.NoneMsgEncoder;
import com.fsy.its.netty.msg.FireObjectInfo;
import com.fsy.its.netty.msg.FireStateMsg;
import com.fsy.its.netty.msg.MsgHead;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.util.Attribute;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

/**
 * 诺帝菲儿9116报警主机解码
 */
@DtuDecoder(brand="Nuodifeier", model="9116")
public class NuodifeierDecoder extends DelimiterBasedFrameDecoder {

    private static final byte[] FRAME_END = {0x0D,0x0A, 0x03};
    private static final int FRAME_MAX_LEN = 1024;
    private static final int FRAME_MIN_LEN = 18;

    @Autowired
    private ApplicationContext applicationContext;

    public NuodifeierDecoder() {
        super(FRAME_MAX_LEN, Unpooled.copiedBuffer(FRAME_END));
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception {
        ByteBuf frame = (ByteBuf) super.decode(ctx, buffer);
        if( frame == null ) {
            return null;
        }
        if( frame.readableBytes() < FRAME_MIN_LEN ) {
            frame.skipBytes(frame.readableBytes());
            return null;
        }

        FireStateMsg fireStateMsg = new FireStateMsg();
        fireStateMsg.head.setCommand(MsgHead.CMD_SEND);
        Attribute<Dtu> attr = ctx.channel().attr(DtuIdDecoder.DTU_KEY);
        fireStateMsg.head.setSrcAddr(attr.get().getId());

        frame.skipBytes(1);
        byte[] data = new byte[frame.readableBytes()];
        frame.readBytes(data);
        //报警主机报上来的内容是一个以gbk编码的字符串
        String content = new String(data, "gbk");
        //每项内容以两个以上空格分隔
        String[] fields = content.split("\\s\\s+");

        //告警或故障
        if( fields[0].equals("FIRE ALARM") ) {
            fireStateMsg.alarm = 1;
        }
        else if( fields[0].equals("TROUBLE") ) {
            fireStateMsg.fault = 1;
        }

        //设备类型
        fireStateMsg.component = new FireObjectInfo();
        fireStateMsg.component.typeName = fields[1];

        //地址描述
        fireStateMsg.component.desc = fields[2];

        //时间
        fireStateMsg.head.time = LocalDateTime.of(
                LocalDate.parse(fields[7], DateTimeFormatter.ofPattern("yyyy/MM/dd")),
                LocalTime.parse(fields[6], DateTimeFormatter.ISO_LOCAL_TIME)
        );

        //设备地址
        fireStateMsg.component.addr = fields[8];

        return fireStateMsg;
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
        ctx.pipeline().addBefore("handler", "noneEncoder", applicationContext.getBean(NoneMsgEncoder.class));
    }
}
